package com.xxxx.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxxx.server.domain.Chapter;
import com.xxxx.server.domain.ChapterExample;
import com.xxxx.server.dto.ChapterDto;
import com.xxxx.server.dto.ChapterPageDto;
import com.xxxx.server.mapper.ChapterMapper;
import com.xxxx.server.util.CopyUtil;
import com.xxxx.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ChapterService {

    @Resource
    private ChapterMapper chapterMapper;

    /**
     * 获取大章（分页）
     * @param chapterPageDto
     */
    public void list(ChapterPageDto chapterPageDto) {
        //  PageHelper只对向下遇到的第一个select语句生效
        PageHelper.startPage(chapterPageDto.getPage(), chapterPageDto.getSize());

        ChapterExample chapterExample = new ChapterExample();
        chapterExample.setOrderByClause("sort asc");
        ChapterExample.Criteria criteria = chapterExample.createCriteria();

        if (!StringUtils.isEmpty(chapterPageDto.getCourseId())) {
            //  按课程id查
            criteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
        }
        List<Chapter> chapterList = chapterMapper.selectByExample(chapterExample);

        //  PageInfo可以获取总行数pageInfo.getTotal()和总页数pageInfo.getPages()
        PageInfo<Chapter> pageInfo = new PageInfo<>(chapterList);
        chapterPageDto.setTotal(pageInfo.getTotal());

        List<ChapterDto> chapterDtoList = CopyUtil.copyList(chapterList, ChapterDto.class);
        chapterPageDto.setList(chapterDtoList);
    }

    /**
     * 保存大章
     * @param chapterDto
     */
    public void save(ChapterDto chapterDto) {
        Chapter chapter = CopyUtil.copy(chapterDto, Chapter.class);
        if (StringUtils.isEmpty(chapterDto.getId())) {
            this.insert(chapter);
        } else {
            this.update(chapter);
        }
    }

    /**
     * 新增大章
     * @param chapter
     */
    private void insert(Chapter chapter) {
        //  设置短uuid
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }

    /**
     * 更新大章（根据id）
     * @param chapter
     */
    private void update(Chapter chapter) {
        chapterMapper.updateByPrimaryKey(chapter);
    }

    /**
     * 删除大章（根据id）
     * @param id
     */
    public void delete(String id) {
        chapterMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据课程id查询大章
     */
    public List<ChapterDto> listByCourse(String courseId) {
        ChapterExample example = new ChapterExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<Chapter> chapterList = chapterMapper.selectByExample(example);
        return CopyUtil.copyList(chapterList, ChapterDto.class);
    }
}
